package com.zkyc.framework.common.aop;

import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author bing.bai
 * @create 2022/6/15
 */
@RestControllerAdvice
@Slf4j
public class GlobalResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    protected ResponseEntity<Object> handlerNotRoleException(Exception ex) {
        ResultVO resultVO;
        //如果是校验报出的异常需要从异常中取出参数校验不通过的信息
        if (ex instanceof MethodArgumentNotValidException) {
            //保存错误提示
            StringBuilder errorMessage = new StringBuilder();
            BindingResult bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
            List<FieldError> errors = bindingResult.getFieldErrors();
            errors.forEach(error ->
                    errorMessage.append(error.getDefaultMessage()).append(";")
            );
            resultVO = ResultVO.fail(errorMessage.substring(0, errorMessage.length() - 1));
        } else {
            resultVO = ResultVO.fail(ResultCode.FAILURE);
        }
        if (!ex.toString().contains("com.netflix.hystrix.exception.HystrixRuntimeException")) {
            log.info("ex", ex);
        }
        return new ResponseEntity<>(resultVO, HttpStatus.OK);
    }
}
